package com.qf.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.entity.TlPerm;
import com.qf.entity.TlUser;
import com.qf.mapper.PermMapper;
import com.qf.mapper.UserMapper;
import com.qf.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class QfUserDetailsService implements UserDetailsService {

    @Autowired
    PermMapper permMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //根据用户名查询到的登录用户
        QueryWrapper<TlUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",name);
        TlUser user=userMapper.selectOne(wrapper);
        //根据用户名查询到的权限
        if(user==null)
            throw new RuntimeException("用户不存在");

        List<TlPerm> perms = permMapper.findByUserName(name);
        //SecurityUser--登录的用户/权限
        SecurityUser securityUser = new SecurityUser();
        securityUser.setLoginUser(user);
        securityUser.setPermissionList(perms);

        //存储权限
        redisTemplate.opsForList().leftPushAll(RedisKey.LOGIN_ADMIN_PERM,perms);
        return securityUser;
    }
}
